package com.xuelang.pipeline.app.pipeline.converter;

import com.xuelang.pipeline.client.pipeline.dto.TriggerSettingDTO;
import com.xuelang.pipeline.client.pipeline.enums.WeekDayEnum;
import com.xuelang.pipeline.client.pipeline.utils.CronExpressionUtils;
import com.xuelang.pipeline.domain.pipeline.TriggerSetting;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;

/**
 * <p>触发配置实体和DTO的转换器</p>
 *
 * @author : yixin.lys
 * @date : 2024-06-12 15:50
 **/
@Mapper
public interface TriggerSettingToDTOConverter {

    TriggerSettingToDTOConverter INSTANCE = Mappers.getMapper(TriggerSettingToDTOConverter.class);

    /**
     * 从DTO转换
     * @param target
     * @return
     */
    TriggerSetting fromDTO(TriggerSettingDTO target);

    @AfterMapping
    default void afterMappingFromDTO(TriggerSettingDTO source, @MappingTarget TriggerSetting target) {
        if (source != null && source.getWeekDay() != null && source.getPeriodTriggerTime() != null) {
            WeekDayEnum dayOfWeek = WeekDayEnum.valueOf(source.getWeekDay());
            String cronExpression = CronExpressionUtils.generateCronExpression(dayOfWeek, source.getPeriodTriggerTime());
            target.setCronExpression(cronExpression);
        }
    }

    /**
     * 转换为DTO
     * @param target
     * @return
     */
    TriggerSettingDTO toDTO(TriggerSetting target);

    @AfterMapping
    default void afterMappingToDTO(TriggerSetting source, @MappingTarget TriggerSettingDTO.TriggerSettingDTOBuilder target) {
        if (source != null && source.getCronExpression() != null) {
            // Extract weekDay and periodTriggerTime from cronExpression
            // Assuming cronExpression follows the pattern "ss mm HH ? * E"
            String[] parts = source.getCronExpression().split(" ");
            if (parts.length == 6) {
                target.periodTriggerTime(parts[2] + ":" + parts[1] + ":" + parts[0]);
                target.weekDay(WeekDayEnum.valueOf(parts[5]).name());
            }
        }
    }
}
